import { fileURLToPath } from 'url'
import { build, preview } from 'vite'
import path from 'path'
import fs from 'fs/promises'

const __dirname = fileURLToPath(new URL('.', import.meta.url))
import Manifest from '../manifest.json' assert { type: "json" };
const isWatching = process.argv[2] === '--watch'

const buildWeb = async () => {
    await build({
        configFile: path.resolve(__dirname, '../vite.config.js'),
        build: {
            watch: isWatching ? {} : undefined,
            lib: {
                entry: 'src/components/Web/index.js',
                formats: ['iife'],
                name: Manifest.id,
                target: 'chrome69',
                fileName: 'web'
            },
            rollupOptions: {
                output: {
                    assetFileNames: (assetInfo) => {
                        if (assetInfo.name === 'style.css') return 'web.css';
                        return assetInfo.name;
                    }
                }
            }
        }
    })
}

const buildMoile = async () => {
    await build({
        configFile: path.resolve(__dirname, '../vite.config.js'),
        build: {
            watch: isWatching ? {} : undefined,
            lib: {
                entry: 'src/components/Mobile/index.js',
                formats: ['iife'],
                name: Manifest.id,
                target: 'chrome69',
                fileName: 'mobile'
            },
            rollupOptions: {
                output: {
                    assetFileNames: (assetInfo) => {
                        if (assetInfo.name === 'style.css') return 'mobile.css';
                        return assetInfo.name;
                    }
                }
            }
        }
    })
}

async function main() {
    try {
        await fs.rm(path.resolve(__dirname, '../dist'), {
            recursive: true
        })
    } catch { }
    await Promise.all([buildWeb(), buildMoile()])
}

async function previewFile() {
    const server = await preview({
        preview: {
            port: 1338,
            host: '0.0.0.0'
        },
    })
    server.printUrls()
}

async function fixCssFile(cssFilePath) {
    let content = await fs.readFile(cssFilePath)
    content = content.toString().replaceAll(':root', ':host')
    await fs.writeFile(cssFilePath, content)
}

main()
    .then(async () => {
        await fs.copyFile(path.resolve(__dirname, '../manifest.json'), path.resolve(__dirname, '../dist/manifest.json'))
        await fixCssFile(path.resolve(__dirname, '../dist/web.css'))
        await fixCssFile(path.resolve(__dirname, '../dist/mobile.css'))
        isWatching && previewFile()
    })
    .catch(console.error)